<?php

namespace JLPay\Services\Cashier;

use JLPay\Services\BaseService;
use JLPay\Models\Cashier\OrderQueryRequest;
use JLPay\Models\Cashier\OrderQueryResponse;
use JLPay\Models\Cashier\PreOrderRequest;
use JLPay\Models\Cashier\PreOrderResponse;
use JLPay\Models\Cashier\TradeCancelRequest;
use JLPay\Models\Cashier\TradeCancelResponse;
use JLPay\Models\Cashier\TradeRefundRequest;
use JLPay\Models\Cashier\TradeRefundResponse;

/**
 * 收银台服务类
 */
class CashierService extends BaseService
{
    /**
     * 获取API URL
     *
     * @param string $requestClass 请求类名
     * @param string|null $apiPath 接口路径
     * @return string 完整的API URL
     */
    public function getApiUrl(string $requestClass, ?string $apiPath = null): string
    {
        $baseUrl = $this->config->getUrl();

        if ($apiPath) {
            return $baseUrl . $apiPath;
        }

        // 使用请求类中定义的API_PREFIX和API_URI
        if (defined($requestClass . '::API_PREFIX') && defined($requestClass . '::API_URI')) {
            $apiPrefix = constant($requestClass . '::API_PREFIX');
            $apiUri = constant($requestClass . '::API_URI');
            
            // 组合API路径
            $path = ltrim($apiPrefix, '/') . '/' . ltrim($apiUri, '/');
            return $baseUrl . '/' . $path;
        }

        // 如果没有定义API_PREFIX和API_URI，使用默认路径
        return $baseUrl . '/open/cashier/trans/trade';
    }

    /**
     * 查询订单状态
     *
     * @param OrderQueryRequest $request 请求对象
     * @return OrderQueryResponse 响应对象
     */
    public function queryOrder(OrderQueryRequest $request): OrderQueryResponse
    {
        return $this->post($request, OrderQueryResponse::class);
    }

    /**
     * 创建预下单
     *
     * @param PreOrderRequest $request 请求对象
     * @return PreOrderResponse 响应对象
     */
    public function createPreOrder(PreOrderRequest $request): PreOrderResponse
    {
        return $this->post($request, PreOrderResponse::class);
    }

    /**
     * 撤销交易
     *
     * @param TradeCancelRequest $request 请求对象
     * @return TradeCancelResponse 响应对象
     */
    public function cancelTrade(TradeCancelRequest $request): TradeCancelResponse
    {
        return $this->post($request, TradeCancelResponse::class);
    }

    /**
     * 退款交易
     *
     * @param TradeRefundRequest $request 请求对象
     * @return TradeRefundResponse 响应对象
     */
    public function refundTrade(TradeRefundRequest $request): TradeRefundResponse
    {
        return $this->post($request, TradeRefundResponse::class);
    }
} 